import Vue from 'vue';
import App from './App';
import VMC from 'vmc/src/install';
import Touch from 'vue-touch';
import Router from 'vue-router';
import Resource from 'vue-resource';
import weixin from 'weixin-js-sdk';
import * as filters from './drivers/filters';
import * as transitions from './drivers/transitions';
import { loadJs, Cache, cache_keys, globalConfigs, setTitle } from './drivers/utils';

// development production
if (process.env.NODE_ENV === 'development') {
    var log = console.log;
    console.log = function() {
        var args = Array.from(arguments);
        args = args.map(arg => {
            try{
                return JSON.parse(JSON.stringify(arg));
            } catch (e) {
                return arg;
            }
        });
   
        log.apply(console, args);
    };
    
    window.vConsole = require('assets/js/vconsole.min');
    require('assets/js/vconsole-resources.min');
    require('assets/js/vconsole-sources.min');
}

Vue.prototype.$configs = globalConfigs;
Vue.prototype.$weixin = weixin;

Object.keys(filters).forEach(name => {
    Vue.filter(name, filters[name]);
});

Object.keys(transitions).forEach(name => {
    let _name = name.replace(/[A-Z](?![A-Z])/g, $0 => '-' + $0.toLowerCase());
    Vue.transition(_name, transitions[name]);
});

Vue.use(Touch);
Vue.use(Resource);
Vue.use(Router);
Vue.use(VMC);

var routes = {};
var req = require.context('../projects/' + process.env.globalConfigs.PROJECT, true, /.*route\.js$/);
req.keys().forEach(p => {
    var r = req(p);
    Object.keys(r).forEach(k => routes[k] = r[k]);
});

var router = new Router();

router.map(routes);

router.redirect({
    '*': '/index'
});

router.beforeEach(t => {
    var title = t.to.doc_title || globalConfigs.BRAND.title;
    setTitle(title);
    
    if (t.to.authorization) {
        var target = { name: t.to.login || 'login', query: {source: t.to.path} };
        
        var oauth = Cache.get(cache_keys.token);
        oauth ? t.next() : t.redirect(target);
    } else {
        t.next();
    }
});

router.start(App, '#app');

var attachFastClick = require('fastclick');
attachFastClick.attach(document.body);